#!/bin/bash
##################
### quickarch1 ###
##################

_script="http://tokland.googlecode.com/svn/trunk/archlinux/arch-bootstrap.sh";
_mirror="ftp://ftp.hosteurope.de/mirror/ftp.archlinux.org";
_mounts="/ /boot swap";
_extrapkgs="haveged grub nano less"
EXIT_STATUS() { echo "ERROR: $@"; exit 1; }

[ "$EUID" != "0" ] && sudo $(readlink -f "$0") "$@";
[ "$EUID" != "0" ] && exit 0;
umount /mnt/* 2>/dev/null;
_arch=$(uname -m 2>/dev/null);
_empty=$(ls /mnt);
[ ! -z "$_empty" ] && EXIT_STATUS "Not empty: /mnt";

echo "Input partitions (/dev/sdX#)";
for _mountpoint in $_mounts;
do
  echo "Mountpoint: ${_mountpoint}";
  read -p "Partition: " input;
  _exist=$(cat /sys/block/*/${input}/partition 2>/dev/null);

  if [ ! -z "$_exist" ] && [[ "$_mountpoint" = /* ]]; 
  then 
    mkdir /mnt${_mountpoint} 2>/dev/null; 
    mount "$input" /mnt${_mountpoint} 2>/dev/null;
    _list="$_list\n${input} ${_mountpoint} ext4 defaults 0 1";
  fi;

  if [ ! -z "$_exist" ] && [ "$_mountpoint" = "swap" ];
  then _list="$_list\n${input} ${_mountpoint} swap defaults 0 0";
  fi;
done;

wget "$_script" -O "arch-bootstrap.sh" || EXIT_STATUS "wget ${_script}";
chmod +x arch-bootstrap.sh || EXIT_STATUS "chmod +x arch-bootstrap.sh"
sed -i "s/EXTRA_PACKAGES=(/&$_extrapkgs /g" arch-bootstrap.sh
./arch-bootstrap.sh -a $_arch -r "$_mirror" /mnt/ || EXIT_STATUS "./arch-bootstrap.sh -a $_arch -r ${_mirror}"
mkdir /mnt/proc /mnt/sys /mnt/dev 2>/dev/null
mount -t proc none /mnt/proc
mount -t sysfs none /mnt/sys
mount -o bind /dev /mnt/dev
mount --bind /dev/pts /mnt/dev/pts

echo '#!/bin/bash' > /mnt/quickarch2
echo "haveged -w 1024" >> /mnt/quickarch2
echo "echo '# This will take a few minutes'" >> /mnt/quickarch2
echo "pacman-key --init" >> /mnt/quickarch2
echo "echo '# Respond to each question with y and [enter]'" >> /mnt/quickarch2
echo "pacman-key --populate archlinux" >> /mnt/quickarch2
echo "pacman-key --refresh-keys" >> /mnt/quickarch2
echo "list=${_list}; for i in \$list; do echo "\""\$i"\"" >> /etc/fstab; done" >> /mnt/quickarch2
echo "pacman --noconfirm -Sfy base arch-install-scripts grub-bios" >> /mnt/quickarch2
echo "loadkeys us" >> /mnt/quickarch2
echo "mkinitcpio -p linux" >> /mnt/quickarch2
echo "echo '# Now install the bootloader'" >> /mnt/quickarch2
chmod +x /mnt/quickarch2

echo "Now chroot in:"
echo "[${USER}@${HOSTNAME}]# chroot /mnt bash"
echo "[chroot] # ./quickarch2"